package com.boarsoft.boar.config.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.boarsoft.config.core.CfgFilePullCallback;
import com.boarsoft.config.core.CfgVarPullCallback;
import com.boarsoft.config.core.ConfigHttpPuller;

public class Main {
	private static final Logger log = LoggerFactory.getLogger(Main.class);
	private static ClassPathXmlApplicationContext ctx;

	public static void main(String[] args) throws Exception {
		ClassLoader cl = Main.class.getClassLoader();
		String root = cl.getResource("").getPath();
		System.out.println(root);
		System.getProperties().put("app.root", root);

		// 通过环境变量配置配置中心地址
		String domain = System.getProperty("config.domain");
		String appId = System.getProperty("app.id", "40284e81688f463901688f47cf1f0000");
		String env = System.getProperty("env", "DEV");
		// int port = Util.str2int(System.getProperty("port", "8083"), 8083);
		//
		// ConfigHttpPuller.pullVars(domain, appId);
		ConfigHttpPuller.pullVars(domain, appId, "boar-flow-demo", env, new CfgVarPullCallback() {
			@Override
			public boolean onReadFailed() {
				// 从配置中心拉取失败时执行，返回true表示中断执行
				return true;
			}

			@Override
			public boolean callback(String k, String v, String p) {
				// k: 变量名，v：变量值，返回true表示已处理
				log.info("Pulled config var {}={}", k, v);
				return false;
			}
		});

		System.out.println(System.getProperty("greeting"));

		// ConfigHttpPuller.pullFiles(domain, appId);
		ConfigHttpPuller.pullFiles(domain, env, "default", appId, "boar-flow-demo", "", "", new CfgFilePullCallback() {
			@Override
			public boolean onReadFailed() {
				// 从配置中心拉取失败时执行，返回true表示中断执行
				return true;
			}

			@Override
			public boolean callback(String code, String type, String content, String path) {
				// k: 变量名，v：变量值，返回true表示已处理
				log.info("Pulled config file {}={}", code, path);
				return false;
			}
		});
		//
		ctx = new ClassPathXmlApplicationContext("classpath:conf/context.xml");
		System.out.println("Startup ".concat(ctx.isRunning() ? "successfully." : "failed."));
	}
}
